﻿// ***********************************************************************
// Assembly         : STX.Admin
// Author           : seven.x
// Created          : 12-26-2013
//
// Last Modified By : seven.x
// Last Modified On : 02-19-2014
// ***********************************************************************
// <copyright file="TabAdministratorController.cs" company="驰创数码">
//     Copyright (c) 驰创数码. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.XPath;
using STX.Lib.Security;
using STX.Service;
using STX.Domain;
using STX.Admin.Models.TabAdministrator;

namespace STX.Admin.Controllers
{
    /// <summary>
    /// Class TabAdministratorController.
    /// </summary>
    public class TabAdministratorController : BasePages1Controller<TabAdministrator, IndexModel, AddModel, EditModel, QueryModel>
    {
        /// <summary>
        /// Gets or sets the tab administrator service.
        /// </summary>
        /// <value>The tab administrator service.</value>
        public TabAdministratorService TabAdministratorService { get; set; }
        /// <summary>
        /// Gets or sets the biz area service.
        /// </summary>
        /// <value>The biz area service.</value>
        public BizAreaService BizAreaService { get; set; }

        /// <summary>
        /// Called when [initialize].
        /// </summary>
        /// <param name="thisService">The this service.</param>
        /// <param name="getIndexModelFunc">The get index model function.</param>
        /// <param name="getAddModelFunc">The get add model function.</param>
        /// <param name="getEditModelFunc">The get edit model function.</param>
        protected override void OnInit(out Func<BaseService<TabAdministrator>> thisService, out Func<IndexModel> getIndexModelFunc, out Func<AddModel> getAddModelFunc, out Func<int, EditModel> getEditModelFunc)
        {
            thisService = () => TabAdministratorService;

            getIndexModelFunc = () => new IndexModel();

            getAddModelFunc = () => new AddModel
            {
                Areas = new SelectList(BizAreaService.FindAll(), "Id", "Name")
            };

            getEditModelFunc = id =>
            {
                var model = TabAdministratorService.FindModelById(id);
                if (model == null)
                {
                    throw new Exception("此用户可能已被删除");
                }
                return new EditModel
                {
                    Id = id,
                    Name = model.Name,
                    Position = model.Position,
                    Username = model.UserName,
                    Areas = new MultiSelectList(BizAreaService.FindAll(), "Id", "Name", model.Areas.Select(o => o.Id).ToArray())
                };
            };
        }

        /// <summary>
        /// Adds the handler.
        /// </summary>
        /// <param name="addModel">The add model.</param>
        /// <returns>System.Int64.</returns>
        protected override long AddHandler(AddModel addModel)
        {
            var model = new STX.Domain.TabAdministrator
            {
                UserName = addModel.Username,
                Password = addModel.Password,
                Name = addModel.Name,
                Position = addModel.Position,
                Areas = addModel.AreaIds==null
                ?new List<BizArea>()
                : BizAreaService.FindAll().Where(o => addModel.AreaIds.Contains(o.Id)).ToList()
            };
            return TabAdministratorService.Add(model);
        }

        /// <summary>
        /// Edits the handler.
        /// </summary>
        /// <param name="editModel">The edit model.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        /// <exception cref="System.Exception">此用户可能已被删除</exception>
        protected override bool EditHandler(EditModel editModel)
        {
            var model = TabAdministratorService.FindModelById(editModel.Id);
            if (model == null)
            {
                throw new Exception("此用户可能已被删除");
            }
            model.Name = editModel.Name;
            if (editModel.Password != "******")
            {
                model.Password = editModel.Password;
            }
            model.Position = editModel.Position;
            model.Areas.Clear();
            model.Areas = editModel.AreaIds==null
                ?new List<BizArea>()
                :BizAreaService.FindAll().Where(o => editModel.AreaIds.Contains(o.Id)).ToList();
            return TabAdministratorService.Update(model);
        }

        /// <summary>
        /// Queries the handler.
        /// </summary>
        /// <param name="queryModel">The query model.</param>
        /// <param name="queryable">The queryable.</param>
        /// <returns>IQueryable{TabAdministrator}.</returns>
        protected override IQueryable<TabAdministrator> QueryHandler(QueryModel queryModel, IQueryable<TabAdministrator> queryable)
        {
            return queryable;
        }

        /// <summary>
        /// Resets the password.
        /// </summary>
        /// <returns>ActionResult.</returns>
        public ActionResult ResetPwd()
        {
            return View();
        }

        /// <summary>
        /// Resets the password.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns>JsonResult.</returns>
        /// <exception cref="System.Exception">
        /// 没有找到此用户
        /// or
        /// 原密码不对
        /// </exception>
        [HttpPost]
        public JsonResult ResetPwd(ResetPwdModel model)
        {
            var curUser = AdminContext.CurrentUser;
            var entity = TabAdministratorService.FindAll().FirstOrDefault(o => o.Id == curUser.Id);
            if (entity == null)
            {
                throw new Exception("没有找到此用户");
            }

            if (entity.Password !=
                HashEncrypt.MD5(string.Format("{0}~!d(ldn:><adDS4&^%{1}", entity.UserName, model.OldPassword)))
            {
                throw new Exception("原密码不对");
            }

            entity.Password = model.NewPassword;
            TabAdministratorService.Update(entity);


            return new JsonResult
            {
                Data = new { success = true }
            };
        }
    }
}
